package managedBean;

import Merlion.FRM.bean.InvoiceAndReceiptBeanRemote;
import Merlion.FRM.bean.PaymentBeanRemote;
import Merlion.FRM.entity.CustomerJournalEntity;
import Merlion.FRM.entity.InvoiceAndReceiptEntity;
import Merlion.FRM.entity.InvoiceLineEntryEntity;
import Merlion.util.state.CustomerJournalState;
import Merlion.util.state.InvoiceAndReceiptState;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import org.primefaces.event.RowEditEvent;

@ManagedBean(name = "PaymentManagedBean")
@ViewScoped
public class PaymentManagedBean implements Serializable {

    private Long invoiceId;
    private Long salesOrderId;
    private String customerName;
    private Collection<InvoiceLineEntryEntity> ilee;
    private Double oldTotalPrice;
    private Double discountRate;
    private Double newTotalPrice;
    private Date dueDate;
    private Date issueDate;
    private int creditTerm;
    private int discountedCreditTerm;
    private Collection<InvoiceAndReceiptState> invoices;
   // private List<CustomerJournalState> customerJournal;
    private List<CustomerJournalState> selectedCustomerJournals;
    private CustomerJournalEntity[] selectedCustomerJournalArray;
    
    //PAYMENT JOURNAL
    private Long paymentId;
    private Long customerJournalId;
    private Long customerId;
    //invoiceId;
    //salesOrderId;
    private Double paymentAmount;
    private Double discountFromCreditTerm;
    private String remarks;
    //END OF PAYMENT JOURNAL ENTITY
    
    private String paymentMethod;
    
    @EJB
    private InvoiceAndReceiptBeanRemote irb;
    @EJB
    private PaymentBeanRemote pbr;
    
    private String issueDateString;
    private String dueDateString;

    /** Creates a new instance of PaymentManagedBean */
    public PaymentManagedBean() {
    }

    public void initView(PhaseEvent event) {
        System.out.println("**PerformManagedBean : initView()");
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);

        invoices = irb.viewOutstandingInvoice();
        // doDisplay(event);
        if(getSelectedCustomerJournals() == null)
            setSelectedCustomerJournals(pbr.viewAllPayment());

    }

    
    public void onEditRow(RowEditEvent event) {
        System.out.println("**PaymentManagedBean: onEditRow()");

        try {
            CustomerJournalState cj = (CustomerJournalState) event.getObject();

            if (cj != null) {
                Long eCustomerJournalId =cj.getCustomerJournalId();
                String eRemarks = cj.getRemarks();

                pbr.editJournal(eCustomerJournalId, eRemarks);
                System.out.println("**PaymentManagedBean :  Payment Journal is successfully edited.");
            } else {
                System.out.println("**PaymentManagedBean: No Journal Record is found. onEditRow() failed.");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    
    public void initViewAddPayment(PhaseEvent event) {
        try {
            if (invoiceId == null) {
                invoiceId = (Long) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("invoiceId");
            }
            if (salesOrderId == null) {
                salesOrderId = (Long) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("salesOrderId");
            }
            if (customerName == null) {
                customerName = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("customerName");
            }
            if (ilee == null) {
                ilee = (Collection<InvoiceLineEntryEntity>) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("ilee");
            }
            if (oldTotalPrice == null) {
                oldTotalPrice = (Double) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("oldTotalPrice");
            }
            if (discountRate == null) {
                discountRate = (Double) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("discountRate");
            }
            if (newTotalPrice == null) {
                newTotalPrice = (Double) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("newTotalPrice");
            }
            if (issueDate == null) {
                issueDate = (Date) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("issueDate");
            }
            if (issueDateString == null) {
                issueDateString = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("issueDateString");
            }
            if (dueDate == null) {
                dueDate = (Date) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("dueDate");
            }
            if (dueDateString == null) {
                dueDateString = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("dueDateString");
            }
            if (creditTerm == 0) {
                creditTerm = (Integer) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("creditTerm");
                // creditTerm = Integer.parseInt(ct);
            }
            if (discountedCreditTerm == 0) {
                discountedCreditTerm = (Integer) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("discountedCreditTerm");
            }
            if (paymentMethod == null) {
                paymentMethod = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("paymentMethod");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void initViewSuccessfulPayment(PhaseEvent event) {
        System.out.println("**PaymentManagedBean: initViewSuccessfulPayment()");
        
        invoiceId = (Long) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("invoiceId");
        setPaymentId((Long) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("paymentId"));
        paymentAmount = (Double) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("paymentAmount");
    }

    //MAKE ACTUAL PAYMENT in performPayment2.xhtml
    public Long doRecordPayment(ActionEvent event) throws IOException {
        System.out.println("**PaymentManagedBean : doRecordPayment()");
        
        Long creditProfileId = pbr.getCreditProfileId(invoiceId);
       
        pbr.performPayment(creditProfileId, invoiceId, newTotalPrice);
        
        Long customerJournalId = pbr.recordPaymentJournal(invoiceId, newTotalPrice);
        try {
          FacesContext.getCurrentInstance().getExternalContext().getFlash().put("invoiceId", invoiceId);
          FacesContext.getCurrentInstance().getExternalContext().getFlash().put("paymentId", customerJournalId);
          FacesContext.getCurrentInstance().getExternalContext().getFlash().put("paymentAmount", newTotalPrice);
          FacesContext.getCurrentInstance().getExternalContext().redirect("SuccessfulPayment.xhtml");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return customerJournalId;  
          
    }

    public void doSearchPayment(ActionEvent event) throws IOException {
        System.out.println("**PaymentManagedBean: doSearchPayment()");
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("invoiceId", invoiceId);
        salesOrderId = pbr.getSalesOrderId(invoiceId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("salesOrderId", salesOrderId);
        customerName = pbr.getCustomerName(invoiceId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("customerName", customerName);
        ilee = pbr.getLineEntry(invoiceId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("ilee", ilee);
        oldTotalPrice = pbr.getTotalPrice(invoiceId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("oldTotalPrice", oldTotalPrice);
        discountRate = pbr.getDiscountRate(invoiceId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("discountRate", discountRate);
        newTotalPrice = pbr.getFinalAmt(invoiceId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("newTotalPrice", getNewTotalPrice());
        paymentMethod = irb.retrievePaymentMethod(invoiceId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("paymentMethod", paymentMethod);
        Long creditProfileId = pbr.getCreditProfileId(invoiceId);
        System.out.println("creditProfileId: " + creditProfileId);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditProfileId", creditProfileId);


        InvoiceAndReceiptEntity ire = pbr.getInvoice(invoiceId);
        issueDate = ire.getIssueDate();
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("issueDate", getIssueDate());
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy");
        setIssueDateString(formatter.format(issueDate));
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("issueDateString", getIssueDateString());


        dueDate = ire.getInvoiceDueDate();
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("dueDate", getDueDate());
        setDueDateString(formatter.format(dueDate));
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("dueDateString", getDueDateString());

        creditTerm = ire.getCreditTerm();
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditTerm", getCreditTerm());
        discountedCreditTerm = ire.getDiscountedCreditTerm();
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("discountedCreditTerm", getDiscountedCreditTerm());

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("PerformPayment2.xhtml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Long getInvoiceId() {
        return invoiceId;
    }

    public void setInvoiceId(Long invoiceId) {
        this.invoiceId = invoiceId;
    }

    public Double getNewTotalPrice() {
        return newTotalPrice;
    }

    public void setNewTotalPrice(Double newTotalPrice) {
        this.newTotalPrice = newTotalPrice;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public PaymentBeanRemote getPbr() {
        return pbr;
    }

    public void setPbr(PaymentBeanRemote pbr) {
        this.pbr = pbr;
    }

    public Long getSalesOrderId() {
        return salesOrderId;
    }

    public void setSalesOrderId(Long salesOrderId) {
        this.salesOrderId = salesOrderId;
    }

    public Double getOldTotalPrice() {
        return oldTotalPrice;
    }

    public void setOldTotalPrice(Double oldTotalPrice) {
        this.oldTotalPrice = oldTotalPrice;
    }

    public Double getDiscountRate() {
        return discountRate;
    }

    public void setDiscountRate(Double discountRate) {
        this.discountRate = discountRate;
    }

    public Collection<InvoiceLineEntryEntity> getIlee() {
        return ilee;
    }

    public void setIlee(Collection<InvoiceLineEntryEntity> ilee) {
        this.ilee = ilee;
    }

    public Date getDueDate() {
        return dueDate;
    }

    public void setDueDate(Date dueDate) {
        this.dueDate = dueDate;
    }

    public Date getIssueDate() {
        return issueDate;
    }

    public void setIssueDate(Date issueDate) {
        this.issueDate = issueDate;
    }

    public int getCreditTerm() {
        return creditTerm;
    }

    public void setCreditTerm(int creditTerm) {
        this.creditTerm = creditTerm;
    }

    public int getDiscountedCreditTerm() {
        return discountedCreditTerm;
    }

    public void setDiscountedCreditTerm(int discountedCreditTerm) {
        this.discountedCreditTerm = discountedCreditTerm;
    }

    public Collection<InvoiceAndReceiptState> getInvoices() {
        return invoices;
    }

    public void setInvoices(Collection<InvoiceAndReceiptState> invoices) {
        this.invoices = invoices;
    }

    public InvoiceAndReceiptBeanRemote getIrb() {
        return irb;
    }

    public void setIrb(InvoiceAndReceiptBeanRemote irb) {
        this.irb = irb;
    }

    public String getIssueDateString() {
        return issueDateString;
    }

    public void setIssueDateString(String issueDateString) {
        this.issueDateString = issueDateString;
    }

    public String getDueDateString() {
        return dueDateString;
    }

    public void setDueDateString(String dueDateString) {
        this.dueDateString = dueDateString;
    }

    public Long getCustomerJournalId() {
        return customerJournalId;
    }

    public void setCustomerJournalId(Long customerJournalId) {
        this.customerJournalId = customerJournalId;
    }

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public List<CustomerJournalState> getSelectedCustomerJournals() {
        return selectedCustomerJournals;
    }

    public void setSelectedCustomerJournals(List<CustomerJournalState> selectedCustomerJournals) {
        this.selectedCustomerJournals = selectedCustomerJournals;
    }

    public CustomerJournalEntity[] getSelectedCustomerJournalArray() {
        return selectedCustomerJournalArray;
    }

    public void setSelectedCustomerJournalArray(CustomerJournalEntity[] selectedCustomerJournalArray) {
        this.selectedCustomerJournalArray = selectedCustomerJournalArray;
    }

    public Double getPaymentAmount() {
        return paymentAmount;
    }

    public void setPaymentAmount(Double paymentAmount) {
        this.paymentAmount = paymentAmount;
    }

    public Double getDiscountFromCreditTerm() {
        return discountFromCreditTerm;
    }

    public void setDiscountFromCreditTerm(Double discountFromCreditTerm) {
        this.discountFromCreditTerm = discountFromCreditTerm;
    }

    public Long getPaymentId() {
        return paymentId;
    }

    public void setPaymentId(Long paymentId) {
        this.paymentId = paymentId;
    }

    public String getPaymentMethod() {
        return paymentMethod;
    }

    public void setPaymentMethod(String paymentMethod) {
        this.paymentMethod = paymentMethod;
    }
    
}
